//
//  RequestData.m
//  RequestData
//
//  Created by dllo on 16/1/7.
//  Copyright © 2016年 HaiTeng. All rights reserved.
//

#import "RequestData.h"
#import "AFHTTPRequestOperationManager.h"


@implementation RequestData

#pragma JSON_RequestData


/**无敌版 GET 或 POST (AFN)*/
///////////////////////////////////////// AFN
/*
 
 post 请求 parameters 填写  字典
 
 get 请求 parameters 填写nil
 
 
 */


+ (void)creatingDataTask:(NSString *)url parameters:(NSDictionary *)parameters Cookie:(NSString *)cookie User_Agent:(NSString *)user_Agent successAFNBlock:(AFNBlock)block {
    
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    manager.securityPolicy.allowInvalidCertificates = NO;
    
    
    if (parameters) {
        
        NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:parameters error:nil];
        
        NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
            if (error) {
                NSLog(@"Error: %@", error);
            } else {
                
                block (responseObject);
            }
        }];
        [dataTask resume];
        
        
    }
    else {
        
        NSMutableURLRequest *request =  [[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:url parameters:parameters error:nil];
        
        [request setValue:cookie forHTTPHeaderField:@"Cookie"];
        
        [request setValue:user_Agent forHTTPHeaderField:@"User-Agent"];
        
        NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
            if (error) {
                NSLog(@"Error: %@", error);
            } else {
                
                block (responseObject);
            }
        }];
        [dataTask resume];
        
        
    }

}





+ (void)GETRequestWithURLString:(NSString *)URLString completionWithSuccess:(void (^)(id result))success WithFailure:(void (^)(id error))failure {
    //    创建对象
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //    设置返回的数据类型
    // 返回NSData 数据类型
    //    manager.responseSerializer = [AFCompoundResponseSerializer serializer];
    // 返回json 数据
    //    注意 默认返回json格式数据
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    //  能接收到返回值类型
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html", nil];
    /**
     * @brief get 解析
     * @param 1 网址
     * @param 2
     * @param 3 responseObject 解析成功的数据
     */
    // 获取沙盒路径
    NSString *doucumentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    // 文件管理器
    NSFileManager *hyManager = [NSFileManager defaultManager];
    // 使用文件管理器创建一个文件夹
    // 2 拼接个文件夹路径
    NSString *htCaches = [doucumentPath stringByAppendingPathComponent:@"htCaches"];
    BOOL hyresult = [hyManager createDirectoryAtPath:htCaches withIntermediateDirectories:YES attributes:nil error:nil];
    if (hyresult == YES) {
                NSLog(@"创建缓存文件夹成功");
    }
    else {
        NSLog(@"创建缓存文件夹失败");
    }
    // 拼接存缓存的路径
    NSString *path = [NSString stringWithFormat:@"%ld.plist", (unsigned long)[URLString hash]];
    // 将这个缓存写在 我自己穿件的文件夹下
    NSString *textFilPath = [htCaches stringByAppendingPathComponent:path];
    
    [manager GET:URLString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        // 解析成功 调用该block方法
        success(responseObject);
        
        //如果数据里有什么东西写不进去, 所以转Data再写入
        NSData *data = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
        BOOL result = [data writeToFile:textFilPath atomically:YES];
        
        NSLog(@"%@",textFilPath);
        if (result == YES) {
            NSLog(@"缓存存入成功");
            
   
        }
        else {
            NSLog(@"缓存存入失败");
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        // 解析出错 调用该block
//        failure(error);
        id resultTemp = [NSData dataWithContentsOfFile:textFilPath];
        id result = [NSJSONSerialization JSONObjectWithData:resultTemp options:0 error:nil];

        failure(result);
    }];
    
}



@end
